import { Component, OnInit, AfterContentChecked, Input, EventEmitter, Output, ContentChild, HostBinding, Optional, Inject } from '@angular/core';

import { FormComponent } from '../form/form.component';
import { Base } from '../../core/view/base';
import { QUERY_PANEL_LAYOUT } from '../keys';

@Component({
  selector: 'bz-query-panel',
  templateUrl: './query-panel.component.html'
})
export class QueryPanelComponent<U, B, S> extends Base<U, B, S> implements OnInit, AfterContentChecked {

  @Input() showSearchText = false;
  @Input() searchText = '';
  @Input() showForm = true;
  @Input() layout: 'top-action' | 'bottom-action';
  @Output() searchTextChange = new EventEmitter();
  @Output() search = new EventEmitter();
  @HostBinding('class.has-form') hasForm = true;
  @HostBinding('class.attract-bottom') attractBottom = true;
  @HostBinding('class.bottom-action-layout') bottomActionLayout = true;

  @ContentChild(FormComponent, { static: true }) formComponent;

  constructor(@Optional() @Inject(QUERY_PANEL_LAYOUT) private defaultLayout: string) {
    super();
  }

  ngOnInit() {
    if (!this.layout) {
      this.layout = <any>this.defaultLayout || 'bottom-action';
    }
    this.attractBottom = this.bottomActionLayout = this.layout === 'bottom-action';
    this.broadcastService.subscribe(<any>'QueryPageCollapse', (collapse) => {
      this.showForm = !collapse;
    });
  }

  ngAfterContentChecked(): void {
    if (!!this.formComponent !== this.hasForm) {
      this.hasForm = !!this.formComponent;
    }

    if (this.formComponent && !this.formComponent.bzLayout) {
      this.formComponent.bzLayout = 'inline-horizontal';
    }
  }
}
